package com.android.camera2.host.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.SystemClock;
import android.util.Log;
import android.util.Size;
import android.view.Display;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.camera2.common.ui.CoverView;
import com.android.camera2.common.ui.MyScrollView;
import com.android.camera2.common.utils.CameraParameter;
import com.android.camera2.common.utils.CameraUtils;
import com.android.camera2.common.utils.LogUtil;
import com.android.camera2.common.app.IApp;
import com.android.camera2.common.ui.FocusView;
import com.android.camera2.common.ui.IAppUi;
import com.android.camera2.common.ui.MySurfaceView;
import com.android.camera2.common.ui.ThumbnailView;
import com.android.camera2.R;

import static android.view.View.GONE;

public class CameraAppUi implements IAppUi,
        View.OnClickListener,
        View.OnTouchListener {

    private static final String TAG = CameraAppUi.class.getSimpleName();

    //app
    private IApp mApp;
    private Size preSize;

    private ImageView iv_shutter;
    private ImageView iv_switch_camera;
    public ThumbnailView iv_display;

    //flash
    private LinearLayout layout_sub_flash;
    private ImageView iv_flash_base;
    private ImageView iv_flash_on;
    private ImageView iv_flash_off;
    private ImageView iv_flash_auto;
    private ImageView iv_torch;

    //ratio
    private LinearLayout layout_sub_ratio;
    private ImageView iv_ratio_base;
    private ImageView iv_ratio_1_1;
    private ImageView iv_ratio_4_3;
    private ImageView iv_ratio_16_9;
    private ImageView iv_ratio_full;
    private ImageView iv_pause_record;

    //focus
    private FocusView mFocusView;
    private MyScrollView mScrollView;
    private LinearLayout mSortliner;

    private ShutterListener mShutterListener;
    private CameraSwitchListener mSwitchListener;
    private FlashStateListener mFlashStateListener;
    private SingleTapListener mSingleTapListener;
    private RatioListener mRatioListener;
    private ModuleChagedLisener mModuleChangedListener;

    private MySurfaceView previewSurfaceView;
    public Chronometer chronometer;
    public ImageView iv_camera_setting;
    private CoverView mCoverView;
    private long cTime = 0;
    private CameraParameter.MODE MODE = CameraParameter.MODE.PHOTO;
    private float mDownX = 0;
    private float mCurX = 0;
    private final static int scroll_photo = 0;
    private final static int scroll_video = 1;
    private boolean isVideoRecording = false;

    public CameraAppUi(IApp app) {
        mApp = app;
    }

    @Override
    public void init() {
        initViewAndListener();
    }

    private void initViewAndListener() {
        previewSurfaceView = mApp.getActivity().findViewById(R.id.surface_preview);
        previewSurfaceView.setClickable(true);
        previewSurfaceView.setOnTouchListener(this);

        ViewGroup rootView = mApp.getActivity().findViewById(R.id.rootView);
        iv_shutter = rootView.findViewById(R.id.iv_shutter);
        iv_shutter.setOnClickListener(this);
        iv_shutter.setOnLongClickListener(longClickListener);
        iv_switch_camera = rootView.findViewById(R.id.iv_switch_camera);
        iv_switch_camera.setOnClickListener(this);
        iv_display = rootView.findViewById(R.id.iv_display);
        //初始化加载上次拍照的最后一thumbnail
        iv_display.setImageBitmap(CameraUtils.getLatestPictureThumbBitmap());
        iv_display.setOnClickListener(this);

        //chronometer
        chronometer = rootView.findViewById(R.id.chronometer);
        chronometer.setBase(SystemClock.elapsedRealtime());
        iv_camera_setting = rootView.findViewById(R.id.iv_camera_setting);
        mCoverView = rootView.findViewById(R.id.iv_cover);
        mCoverView.hideCover();

        //scrollview
        mScrollView = rootView.findViewById(R.id.myScrollView);
        mScrollView.setOnScrollerItemClcikListener(onScrollerItemClcikListener);
        mScrollView.setOnScrollListener(listener);
        mSortliner = rootView.findViewById(R.id.sortliner);
        mScrollView.initScrollChildView(mSortliner);
        iv_pause_record = rootView.findViewById(R.id.iv_pause_record);
        iv_pause_record.setOnClickListener(this);

        //flash
        layout_sub_flash = rootView.findViewById(R.id.layout_sub_flash);
        iv_flash_base = rootView.findViewById(R.id.iv_flash_base);
        iv_flash_base.setOnClickListener(this);
        iv_flash_on = rootView.findViewById(R.id.iv_flash_on);
        iv_flash_on.setOnClickListener(this);
        iv_flash_off = rootView.findViewById(R.id.iv_flash_off);
        iv_flash_off.setOnClickListener(this);
        iv_flash_auto = rootView.findViewById(R.id.iv_flash_auto);
        iv_flash_auto.setOnClickListener(this);
        iv_torch = rootView.findViewById(R.id.iv_torch);
        iv_torch.setOnClickListener(this);

        //ratio
        layout_sub_ratio = rootView.findViewById(R.id.layout_sub_ratio);
        iv_ratio_base = rootView.findViewById(R.id.iv_ratio_base);
        iv_ratio_base.setOnClickListener(this);
        iv_ratio_1_1 = rootView.findViewById(R.id.iv_ratio_1_1);
        iv_ratio_1_1.setOnClickListener(this);
        iv_ratio_4_3 = rootView.findViewById(R.id.iv_ratio_4_3);
        iv_ratio_4_3.setOnClickListener(this);
        iv_ratio_16_9 = rootView.findViewById(R.id.iv_ratio_16_9);
        iv_ratio_16_9.setOnClickListener(this);
        iv_ratio_full = rootView.findViewById(R.id.iv_ratio_full);
        iv_ratio_full.setOnClickListener(this);


        //FocusView
        mFocusView = new FocusView(mApp.getActivity());
        mFocusView.setVisibility(GONE);
        rootView.addView(mFocusView);
    }

    private MyScrollView.OnScrollerItemClcikListener onScrollerItemClcikListener = new MyScrollView.OnScrollerItemClcikListener() {
        @Override
        public void onItemClick(View v, int position) {
            LogUtil.i(TAG, "view = " + v);
            getCenterItem(v);
            switch (position) {
                case scroll_photo:
                    LogUtil.i(TAG, "s_photo_");
                    MODE = CameraParameter.MODE.PHOTO;
                    handleModeChangeForUi(false);
                    mModuleChangedListener.onModuleChanged(MODE);
                    break;
                case scroll_video:
                    LogUtil.i(TAG, "s_video_");
                    MODE = CameraParameter.MODE.VIDEO;
                    handleModeChangeForUi(false);
                    mModuleChangedListener.onModuleChanged(MODE);
                    break;
            }
        }
    };

    private void getCenterItem(View view) {
        // 获取horizontalScrollView的宽度
        int hsvWidth = mScrollView.getWidth();
        int textViewLeft = view.getLeft();
        int textViewWidth = view.getWidth();
        LogUtil.i(TAG, "textViewLeft = " + textViewLeft + "\n textViewWidth = " + textViewWidth + "\n hsvWidth = " + hsvWidth);
        // 计算偏移量
        int offset = textViewLeft + textViewWidth - hsvWidth / 2;

        // 横向平滑滚动偏移
        LogUtil.e(TAG, "offset = " + offset);
        mScrollView.smoothScrollTo(offset, 0);
        LogUtil.i(TAG, "performItemClick = " + ((TextView) view).getText());
    }


    @Override
    public void resume() {
        LogUtil.i(TAG, "resume");
    }

    @Override
    public void pause() {
        layout_sub_ratio.setVisibility(GONE);
        isVideoRecording = false;
        LogUtil.i(TAG, "pause");
    }

    @Override
    public void destroy() {
        LogUtil.i(TAG, "destroy");
        isVideoRecording = false;
    }

    @Override
    public void setPrevSurfaceListener(SurfaceHolder.Callback callback) {
        //设置预览监听回调
        LogUtil.i(TAG, "has been set PrevSurfaceListener" + callback);
//        previewSurfaceCallback = callback;
        if (callback != null) {
            previewSurfaceView.getHolder().addCallback(callback);
        }
    }

    private View.OnLongClickListener longClickListener = new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            mShutterListener.onShutterLongPressed();
            return false;

        }
    };


    @Override
    public void setPreviewSize(Size size) {
        LogUtil.e(TAG, "setPreviewSize = " + size);
        preSize = size;

        Display display = mApp.getActivity().getWindowManager().getDefaultDisplay();
        int width = display.getWidth();
        int height = display.getHeight();
        Log.i(TAG, "width = " + width + ",height = " + height);
        mFocusView.initFocusArea(width, height);
        mApp.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                previewSurfaceView.getHolder().setFixedSize(preSize.getWidth(), preSize.getHeight());
                previewSurfaceView.setAspectRation(preSize.getWidth(), preSize.getHeight());
            }
        });

    }


    @Override
    public void setShutterListener(ShutterListener listener) {
        mShutterListener = listener;
    }

    @Override
    public void setCameraSwitcherListener(CameraSwitchListener listener) {
        mSwitchListener = listener;
    }

    @Override
    public void displayThumbnail(Bitmap b) {
        final Bitmap bitmap = b;
        mApp.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                iv_display.setImageBitmap(bitmap);
            }
        });
    }

    @Override
    public void setFlashStateListener(FlashStateListener listener) {
        mFlashStateListener = listener;
    }

    @Override
    public FocusView getFocusView() {
        return mFocusView;
    }

    @Override
    public MySurfaceView getPreviewSurface() {
        assert previewSurfaceView != null;
        return previewSurfaceView;
    }

    @Override
    public CoverView getCoverView() {
        return mCoverView;
    }

    @Override
    public void setSingleTapLister(SingleTapListener singleTapListener) {
        mSingleTapListener = singleTapListener;
    }

    @Override
    public void setRatioListener(RatioListener ratioListener) {
        mRatioListener = ratioListener;
    }

    @Override
    public void setOnModuleChangedListener(ModuleChagedLisener listener) {
        mModuleChangedListener = listener;
    }

    public SingleTapListener getSingleTapListener() {
        return mSingleTapListener;
    }

    @SuppressLint("WrongConstant")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_shutter:
                if (mShutterListener != null) {
                    handleModeChangeForUi(true);
                    mShutterListener.onShutterPressed();
                }
                break;
            case R.id.iv_switch_camera:
                if (CameraUtils.getInstance().doubleClickTimeoutCheck()) {
                    return;
                }
                if (mSwitchListener != null) {
                    mSwitchListener.onCameraSwitch();
                }
                break;
            case R.id.iv_display:
                handleClickThunbnail();
                break;
            //flash
            case R.id.iv_flash_base:
                layout_sub_flash.setVisibility((layout_sub_flash.getVisibility()) == View.VISIBLE ? View.INVISIBLE : View.VISIBLE);
                layout_sub_ratio.setVisibility(View.INVISIBLE);
                break;
            case R.id.iv_flash_on:
                handleState(CameraParameter.TPYE.FLASH, R.drawable.ic_flash_on, Color.YELLOW);
                mFlashStateListener.flashOn();
                break;
            case R.id.iv_flash_auto:
                handleState(CameraParameter.TPYE.FLASH, R.drawable.ic_flash_auto, Color.YELLOW);
                mFlashStateListener.flashAuto();
                break;
            case R.id.iv_torch:
                handleState(CameraParameter.TPYE.FLASH, R.drawable.ic_torch, Color.YELLOW);
                mFlashStateListener.flashTroch();
                break;
            case R.id.iv_flash_off:
                handleState(CameraParameter.TPYE.FLASH, R.drawable.ic_flash_off, Color.WHITE);
                mFlashStateListener.flashOff();
                break;

            //ratio
            case R.id.iv_ratio_base:
                layout_sub_ratio.setVisibility((layout_sub_ratio.getVisibility()) == View.VISIBLE ? View.INVISIBLE : View.VISIBLE);
                layout_sub_flash.setVisibility(View.INVISIBLE);
                break;
            case R.id.iv_ratio_1_1:
                mRatioListener.ratio_1_1();
                handleState(CameraParameter.TPYE.RATIO, R.drawable.ratio_1_1);
                break;
            case R.id.iv_ratio_4_3:
                mRatioListener.ratio_4_3();
                handleState(CameraParameter.TPYE.RATIO, R.drawable.ratio_4_3);
                break;
            case R.id.iv_ratio_16_9:
                mRatioListener.ratio_16_9();
                handleState(CameraParameter.TPYE.RATIO, R.drawable.ratio_16_9);
                break;
            case R.id.iv_ratio_full:
                mRatioListener.ratio_full();
                handleState(CameraParameter.TPYE.RATIO, R.drawable.ratio_full);
                break;

        }
    }

    private void handleClickThunbnail() {
//      Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
//      Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        Intent i = new Intent(Intent.ACTION_PICK);
        if (MODE == CameraParameter.MODE.VIDEO) {
            i.setType("video/*");
        } else {
            i.setType("image/*");
        }
        mApp.getActivity().startActivity(i);
    }

    private void handleModeChangeForUi(boolean isShutterClick) {
        LogUtil.i(TAG, "mode = " + MODE);
        Drawable d;

        if (isShutterClick && MODE == CameraParameter.MODE.VIDEO) {
            if (isVideoRecording) {
                LogUtil.i(TAG, "stopRecording");
                d = mApp.getActivity().getResources().getDrawable(R.drawable.ic_video);
                iv_shutter.setBackground(d);
                chronometer.setVisibility(View.INVISIBLE);
                iv_switch_camera.setVisibility(View.VISIBLE);
                iv_pause_record.setVisibility(GONE);
                iv_display.setVisibility(View.VISIBLE);
                isVideoRecording = false;
            } else {
                LogUtil.i(TAG, "startRecording");
                d = mApp.getActivity().getResources().getDrawable(R.drawable.ic_start_recoding);
                iv_shutter.setBackground(d);
                chronometer.setVisibility(View.VISIBLE);
                iv_switch_camera.setVisibility(View.INVISIBLE);
                iv_pause_record.setVisibility(View.VISIBLE);
                iv_display.setVisibility(View.INVISIBLE);
                isVideoRecording = true;
            }
        } else {
            if (MODE == CameraParameter.MODE.PHOTO) {
                iv_ratio_base.setVisibility(View.VISIBLE);
                chronometer.setVisibility(View.INVISIBLE);
                d = mApp.getActivity().getResources().getDrawable(R.drawable.ic_capture);
                iv_shutter.setBackground(d);
            } else if (MODE == CameraParameter.MODE.VIDEO) {
                layout_sub_ratio.setVisibility(GONE);
                iv_ratio_base.setVisibility(GONE);
                d = mApp.getActivity().getResources().getDrawable(R.drawable.ic_video);
                iv_shutter.setBackground(d);
            }
        }


    }

    private MyScrollView.OnScrollListenerForUser listener = new MyScrollView.OnScrollListenerForUser() {
        @Override
        public void onRight() {
            LogUtil.i(TAG, "onRight");
        }

        @Override
        public void onLeft() {
            LogUtil.i(TAG, "onLeft");
        }

        @Override
        public void onScroll() {
            LogUtil.i(TAG, "onScroll");
        }
    };

    /**
     * handle flash and ratio ui state change
     *
     * @param type  handle type
     * @param draw  display resource
     * @param color display color
     */
    private void handleState(CameraParameter.TPYE type, int draw, int... color) {
        if (type == CameraParameter.TPYE.FLASH) {
            iv_flash_base.setBackgroundTintList(ColorStateList.valueOf(color[0]));
            Drawable drawable = mApp.getActivity().getResources().getDrawable(draw);
            iv_flash_base.setBackground(drawable);
            layout_sub_flash.setVisibility(View.INVISIBLE);
        } else if (type == CameraParameter.TPYE.RATIO) {
//            iv_ratio_base.setBackgroundTintList(ColorStateList.valueOf(color[0]));
            Drawable drawable = mApp.getActivity().getResources().getDrawable(draw);
            iv_ratio_base.setBackground(drawable);
            layout_sub_ratio.setVisibility(View.INVISIBLE);
        }
    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        //swipe left and right
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mDownX = event.getX();
                break;
            case MotionEvent.ACTION_MOVE:
                mCurX = event.getX();
                break;
            case MotionEvent.ACTION_UP:
                float value = mCurX - mDownX;
                if (value > 0 && Math.abs(value) > 100) {
                    LogUtil.e(TAG, "右滑动--");
                    // Handle left sidling logic
                    MODE = CameraParameter.MODE.PHOTO;
                    handleModeChangeForUi(false);
                    mModuleChangedListener.onModuleChanged(MODE);
                    return true;
                } else if (value < 0 && Math.abs(value) > 100) {
                    // Handle right sidling logic
                    LogUtil.e(TAG, "左滑动--");
                    MODE = CameraParameter.MODE.VIDEO;
                    handleModeChangeForUi(false);
                    mModuleChangedListener.onModuleChanged(MODE);
                    return true;
                }
                break;
        }
        //Handle singleTap
        LogUtil.i(TAG, "getSurfaceView--->width = " + previewSurfaceView.getWidth() + "height = " + previewSurfaceView.getHeight());
        float windowHeight = mApp.getActivity().getWindowManager().getDefaultDisplay().getHeight();
        float dealHeight = (windowHeight - previewSurfaceView.getHeight()) / 2;
        float w = event.getX();
        float h = event.getY() + dealHeight;

        int LimitTop = (int) dealHeight + mApp.getActivity().getResources().getDimensionPixelSize(R.dimen.radius_outer);
        int LimitBottom = previewSurfaceView.getHeight() + (int) dealHeight - mApp.getActivity().getResources().getDimensionPixelSize(R.dimen.radius_outer);
        int LimitLeft = previewSurfaceView.getLeft() + mApp.getActivity().getResources().getDimensionPixelSize(R.dimen.radius_outer);
        int LimitRight = previewSurfaceView.getRight() - mApp.getActivity().getResources().getDimensionPixelSize(R.dimen.radius_outer);
        LogUtil.i(TAG, "onTouch--->" + "x = " + w + "y = " + h);

        //Limit Focus boundary
        if (w < LimitLeft) {
            w = LimitLeft;
        }
        if (w > LimitRight) {
            w = LimitRight;
        }
        if (h < LimitTop) {
            h = LimitTop;
        }
        if (h > LimitBottom) {
            h = LimitBottom;
        }

        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            cTime = System.currentTimeMillis();
        }
        if (event.getAction() == MotionEvent.ACTION_UP) {
            if (System.currentTimeMillis() - cTime > 500) {
                mSingleTapListener.onLongSingleTap(w, h);
            } else {
                mSingleTapListener.onSingleTap(w, h);
            }
        }
        return false;
    }


}
